package com.zh.search.Thread;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class FixedThreadPool {

    public static ThreadPoolExecutor fixedThreadPool =
            new ThreadPoolExecutor(
                    4,
                    6,
                    60,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(7),
                    new CustomThreadFactory("work"),
                    new ThreadPoolExecutor.CallerRunsPolicy());

    static class CustomThreadFactory implements ThreadFactory {
        private final String namePrefix;
        private final AtomicInteger threadId = new AtomicInteger(1);

        public CustomThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix;
        }

        @Override
        public Thread newThread(@NotNull Runnable r) {
            Thread t = new Thread(r, namePrefix + "-thread-" + threadId.getAndIncrement());
            t.setDaemon(false); // 设置为非守护线程
            t.setPriority(Thread.NORM_PRIORITY); // 设置线程优先级
            return t;
        }
    }
}
